package com.wuyou.mybatishandlerdemo.config;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import java.sql.Connection;

/**
 * DataPermissionInterceptor
 *
 * @Date 2025-09-25 16:11
 * @Author 无忧
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
@Component
public class DataPermissionInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

        if(mappedStatement.getSqlCommandType() == SqlCommandType.INSERT){
            return invocation.proceed();
        }
        // 获取原始SQL
        BoundSql boundSql = statementHandler.getBoundSql();
        String originalSql = boundSql.getSql();

        // 添加数据权限过滤条件
        String modifiedSql = addDataPermission(originalSql, mappedStatement.getId());

        // 修改SQL
        metaObject.setValue("delegate.boundSql.sql", modifiedSql);

        return invocation.proceed();
    }

    private String addDataPermission(String sql, String mapperId) {
        // 根据当前用户权限动态添加WHERE条件
        String userId = "1";
        String deptId = "1";
        String tenantId = "1";
        if (sql.toLowerCase().contains("where")) {
            return sql + " AND tenant_id = '" + tenantId + "'";
        } else {
            return sql + " WHERE tenant_id = '" + tenantId + "'";
        }
    }
}
